<?php
namespace app\controller;

use app\BaseController;
use app\Model\PlatformConfigModel;
use think\facade\Request;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\Snowflake;

class PlatformConfig extends BaseController
{
    /**
     * 平台配置列表
     * @return \think\response\Json
     */
    public function list()
    {
        $platformName = Request::get('platform_name');
        $page = Request::get('page', 1);
        $limit = Request::get('limit', 10);
        $query = PlatformConfigModel::order('id', 'desc');
        if ($platformName) {
            $query->where('platform_name', 'like', '%' . $platformName . '%');
        }
        $list = $query->paginate([
            'list_rows' => $limit,
            'page' => $page
        ]);
        return json(['code' => 0, 'msg' => '获取配置列表成功', 'data' => $list]);
    }

    /**
     * 新增平台配置
     * @return \think\response\Json
     */
    public function create()
    {
        $data = Request::post();
        // 验证必填字段
        if (empty($data['platform_name']) || empty($data['version']) || empty($data['download_url']) || empty($data['md5_value'])) {
            return json(['code' => 1, 'msg' => '平台名称、版本号、下载地址和 MD5 值为必填项']);
        }
        $snowflake = new Snowflake(1, 1);
        $data['platform_config_id'] = $snowflake->nextId();

        try {
            $platformConfig = new PlatformConfigModel();
            $platformConfig->save($data);
            return json(['code' => 0, 'msg' => '新增配置成功', 'data' => $platformConfig]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '新增配置失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取平台配置详情
     * @param $id
     * @return \think\response\Json
     */
    public function detail($id)
    {
        try {
            $platformConfig = PlatformConfigModel::find($id);
            if ($platformConfig) {
                return json(['code' => 0, 'msg' => '获取配置详情成功', 'data' => $platformConfig]);
            } else {
                return json(['code' => 1, 'msg' => '未找到该配置信息']);
            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取配置详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 编辑平台配置
     * @param $id
     * @return \think\response\Json
     */
    public function update($id)
    {
        $data = Request::put();
        // 验证必填字段
        if (empty($data['platform_name']) || empty($data['version']) || empty($data['download_url']) || empty($data['md5_value'])) {
            return json(['code' => 1, 'msg' => '平台名称、版本号、下载地址和 MD5 值为必填项']);
        }
        try {
            $platformConfig = PlatformConfigModel::find($id);
            if ($platformConfig) {
                $platformConfig->save($data);
                return json(['code' => 0, 'msg' => '编辑配置成功', 'data' => $platformConfig]);
            } else {
                return json(['code' => 1, 'msg' => '未找到该配置信息']);
            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '编辑配置失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除平台配置
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id)
    {
        try {
            $platformConfig = PlatformConfigModel::find($id);
            if ($platformConfig) {
                $platformConfig->delete();
                return json(['code' => 0, 'msg' => '删除配置成功']);
            } else {
                return json(['code' => 1, 'msg' => '未找到该配置信息']);
            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除配置失败：' . $e->getMessage()]);
        }
    }

    /**
     * 导入平台配置
     * @return \think\response\Json
     */
    public function import()
    {
        $file = Request::file('file');
        if (!$file) {
            return json(['code' => 1, 'msg' => '请上传文件']);
        }
        $ext = $file->getOriginalExtension();
        if (!in_array($ext, ['txt', 'csv', 'xls'])) {
            return json(['code' => 1, 'msg' => '只支持 txt、csv、xls 文件']);
        }
        try {
            $path = $file->getPathname();
            // 这里需要根据文件类型解析文件内容并入库
            // 示例代码暂未实现具体解析逻辑
            return json(['code' => 0, 'msg' => '导入配置成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '导入配置失败：' . $e->getMessage()]);
        }
    }

    /**
     * 导出平台配置
     * @return \think\response\Json
     */
    public function export()
    {
        $params = Request::get();
        $query = PlatformConfigModel::order('id', 'desc');
        if (isset($params['platform_name'])) {
            $query->where('platform_name', 'like', '%' . $params['platform_name'] . '%');
        }
        $list = $query->select();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', '主键ID');
        $sheet->setCellValue('B1', '雪花ID');
        $sheet->setCellValue('C1', '平台名称');
        $sheet->setCellValue('D1', '版本号');
        $sheet->setCellValue('E1', '下载地址');
        $sheet->setCellValue('F1', 'MD5值');
        $sheet->setCellValue('G1', '创建时间');
        $sheet->setCellValue('H1', '更新时间');

        $row = 2;
        foreach ($list as $item) {
            $sheet->setCellValue('A' . $row, $item->id);
            $sheet->setCellValue('B' . $row, $item->platform_config_id);
            $sheet->setCellValue('C' . $row, $item->platform_name);
            $sheet->setCellValue('D' . $row, $item->version);
            $sheet->setCellValue('E' . $row, $item->download_url);
            $sheet->setCellValue('F' . $row, $item->md5_value);

            $createTime = $item->create_time ? \DateTime::createFromFormat('Y-m-d H:i:s', $item->create_time) : null;
            $sheet->setCellValue('G' . $row, $createTime ? $createTime->format('Y-m-d H:i:s') : '');

            $updateTime = $item->update_time ? \DateTime::createFromFormat('Y-m-d H:i:s', $item->update_time) : null;
            $sheet->setCellValue('H' . $row, $updateTime ? $updateTime->format('Y-m-d H:i:s') : '');

            $row++;
        }

        $format = Request::get('format', 'xls'); // 默认导出格式改为 xls
        // 设置输出参数
        $filename = 'platform_config_' . date('YmdHis');

        if ($format == 'csv') {
            $writer = new Csv($spreadsheet);
            $filename .= '.csv';
            header('Content-Type: text/csv');
        } else {
            $writer = new Xlsx($spreadsheet);
            $filename .= '.xlsx';
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        }
        // 输出文件
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        exit;
    }


}    